import axios from "axios"
import store from "../store"
import {ElMessage} from "element-plus";
import { isCheckTimeout } from "./auth";
import { TOKEN_EXPIRE_CODE } from "../constant";

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
})

//请求拦截器
service.interceptors.request.use(config => {
    if (store.getters.token) {
        if (isCheckTimeout()) {
            //退出操作
            store.dispatch("user/logout")
            return Promise.reject(new Error("token 失效"))
        }
        config.headers.Authorization = `${store.getters.token}`
    }
    return config
}, error => {
    return Promise.reject(error)
})

//响应连接器
service.interceptors.response.use(
    response => {
        const {code, msg, data, time} = response.data
        if (code === 200) {
            return data
        }else if (code === 401) {
            store.dispatch("user/logout")
            ElMessage.error(msg)
            console.log(msg)

            return Promise.reject(new Error(msg))
        } else {
            ElMessage.error(msg)
            return Promise.reject(new Error(msg))
        }
    },
    error => {
        if (error.resolve() && error.response.data && error.response.data.code === TOKEN_EXPIRE_CODE) {
            store.dispatch("user/logout")
        }
        ElMessage.error(error.message)
        console.log(error)

        return Promise.reject(error)
    }
)


export default service